﻿using System;
using System.IO;
using System.Linq;
using Assist;
using Autodesk.Revit.DB;
using YArchitech.Revit;
using HYFamilyLibDataManager;

namespace HYOpeningCommon.DbOpening
{
	public abstract class DbFamilyOpening : DbOpeningBase
	{
		public void SetFamilyName(string strFamilyName)
		{
			this.m_strFamilyName = strFamilyName;
		}

		public virtual bool LoadOpeningFamily(Autodesk.Revit.DB.Document doc, ref FamilySymbol familySymbol)
		{
			Family family = ElementFiltering.FindFamily(doc, this.m_strFamilyName);
			if (family != null)
			{
				familySymbol = family.GetSymbols().FirstOrDefault<FamilySymbol>();
				return true;
			}
			string text = Path.Combine(FamilyLibDatabase.GetDefFamilyLibPath(), string.Concat(new string[]
			{
				"Family\\",
				RevitVersion.Version,
				"\\Opening\\",
				this.m_strFamilyName,
				".rfa"
			}));
			Family family2 = null;
			try
			{
				Transaction transaction = new Transaction(doc, "LoadFamily");
				try
				{
					transaction.Start();
					if (!doc.LoadFamily(text, out family2))
					{
						transaction.RollBack();
						return false;
					}
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
					return false;
				}
				familySymbol = family2.GetSymbols().FirstOrDefault<FamilySymbol>();
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		private string m_strFamilyName;
	}
}
